import com.cloudera.api.ApiUtils;
import com.cloudera.api.ClouderaManagerClientBuilder;
import com.cloudera.api.DataView;
import com.cloudera.api.model.*;
import com.cloudera.api.v10.HostsResourceV10;
import com.cloudera.api.v18.RootResourceV18;
import com.cloudera.api.v18.ServicesResourceV18;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Example {

    public static void main(String[] args) {
        String CMS_HOST = "10.87.229.25";
        int CMS_PORT = 7180;
        String CMS_USER = "admin";
        String CMS_PASSWORD = "admin";
        String CLUSTER_NAME = "Cluster";
        // 创建 Cloudera Manager 客户端
        RootResourceV18 apiRoot = new ClouderaManagerClientBuilder()
                .withHost(CMS_HOST)
                .withUsernamePassword(CMS_USER, CMS_PASSWORD)
                .build()
                .getRootV18();
        // 获取服务资源
        ServicesResourceV18 servicesResource = apiRoot.getClustersResource().getServicesResource(CLUSTER_NAME);
        String[] servers = {"zookeeper","hdfs","kafka2","yarn","hive","hue","spark_on_yarn","hbase"};
        for (String server: servers) {
            // 获取群集上的服务
            ApiService service = servicesResource.readService(server, DataView.SUMMARY);
            System.out.println(service.getName() + " - " + service.getHealthSummary());
        }




        HostsResourceV10 hostsResource = apiRoot.getHostsResource();

        // 获取所有主机
        ApiHostList apiHosts = hostsResource.readHosts(DataView.FULL);

        String from = "2023-05-11 14:20:00";
        String end = "2023-05-11 14:45:00";
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date fromDate = null;
        Date toDate = null;
        try {
            fromDate = dfs.parse(from);
            toDate = dfs.parse(end);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        String fromformat = ApiUtils.printDate(fromDate);
        String toformat = ApiUtils.printDate(toDate);
        Set<String> ifs = new HashSet<>();
        ifs.add("all");

        Set<String> metricSet = new HashSet<>();

        // 打印每个主机的内存使用情况
        for (ApiHost host : apiHosts.getHosts()) {
            ApiMetricList metrics = hostsResource.getMetrics(host.getHostId(), fromformat, toformat, true, ifs, true, ifs, metricSet, DataView.EXPORT);
            List<ApiMetric> metricsList = metrics.getMetrics();
            System.out.println(host.getHostname() + " - Used memory: " + metricsList.get(0).getData() + " bytes");
        }
    }
}
